from app.common.where_op_symbol import WhereOpSymbol


def to_and_filter(condition: dict, op: str, ignore_dict_key: list[str] = None) -> dict | None:
    """
    将Python字典转换为ChromaDB的AND条件过滤
    :param op: 字典项操作符
    :param ignore_dict_key: 忽略的属性key
    :param condition: 查询条件
    :return: dict
    """
    result = _to_filter_item(condition, op, ignore_dict_key=ignore_dict_key)
    return None if not result else {WhereOpSymbol.AND: result}


def to_or_filter(condition: dict, op: str, ignore_dict_key: list[str] = None) -> dict:
    """
    将Python字典转换为ChromaDB的OR条件过滤
    :param condition: 过滤条件
    :param op: 操作符
    :param ignore_dict_key: 忽略的key
    :return: list[dict]
    """
    result = _to_filter_item(condition, op, ignore_dict_key)
    return None if not result else {WhereOpSymbol.OR: result}


def _to_filter_item(condition: dict, op: str, ignore_dict_key: list[str] = None) -> list[dict] | None:
    """
    将条件字典转换为过滤条件item数组
    :param condition: 过滤条件
    :param op: 操作符
    :param ignore_dict_key: 忽略的key
    :return: list[dict]
    """
    if condition is None:
        return None
    result = []
    for key, val in condition.items():
        if ignore_dict_key is not None and key in ignore_dict_key:
            continue
        result.append({
            key: {
                op: val,
            }
        })
    return result
